class Api::V1::FavoritesController < Api::V1::BaseController
  def index
    @favorites = @current_user.favorites.where(favoriteable_type: params[:type]).order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def create
    if params[:id].blank?
      render json: { result: false, message: '缺少参数.' }, status: :unprocessable_entity
    else
      if params[:type] == 'Spu'
        spu = Spu.find params[:id]
        if spu.blank?
          render json: { result: false, message: '商品不存在.' }, status: :unprocessable_entity
        else
          @favorite = Favorite.where(favoriteable_type: "Spu", favoriteable_id: params[:id]).first
          if @favorite.blank?
            Favorite.create(favoriteable_type: "Spu", favoriteable_id: params[:id], user_id: @current_user.id)
            render json: { result: true, message: '收藏成功.' }, status: :ok
          else
            @favorite.destroy
            render json: { result: true, message: '取消收藏成功.' }, status: :ok
          end
        end
      elsif params[:type] == 'Shop'
        shop = Shop.find params[:id]
        if shop.blank?
          render json: { result: false, message: '店铺不存在.' }, status: :unprocessable_entity
        else
          @favorite = Favorite.where(favoriteable_type: "Shop", favoriteable_id: params[:id]).first
          if @favorite.blank?
            Favorite.create(favoriteable_type: "Shop", favoriteable_id: params[:id], user_id: @current_user.id)
            render json: { result: true, message: '收藏成功.' }, status: :ok
          else
            @favorite.destroy
            render json: { result: true, message: '取消收藏成功.' }, status: :ok
          end
        end
      elsif params[:type] == 'Brand'
        brand = Brand.find params[:id]
        if brand.blank?
          render json: { result: false, message: '品牌不存在.' }, status: :unprocessable_entity
        else
          @favorite = Favorite.where(favoriteable_type: "Brand", favoriteable_id: params[:id]).first
          if @favorite.blank?
            Favorite.create(favoriteable_type: "Brand", favoriteable_id: params[:id], user_id: @current_user.id)
            render json: { result: true, message: '收藏成功.' }, status: :ok
          else
            @favorite.destroy
            render json: { result: true, message: '取消收藏成功.' }, status: :ok
          end
        end
      else
        render json: { result: false, message: '收藏类型不正确.' }, status: :unprocessable_entity
      end
    end
  end

end
